package com.tang.netty.aio.server;

import com.tang.netty.aio.ChannelAdapter;
import com.tang.netty.aio.ChannelHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * 处理消息
 *
 * @author fulin.tang
 * @version V1.0
 * @since 2021/8/10
 */
@Slf4j
public class AioServerHandler extends ChannelAdapter {

    public AioServerHandler(AsynchronousSocketChannel channel, Charset charset) {
        super(channel, charset);
    }

    @Override
    public void channelActive(ChannelHandler ctx) {
        try {
            log.info("有新的客户端连接：{}", ctx.channel().getRemoteAddress());
            // 通知客户端连接建立成功
            ctx.writeAndFlush("连接服务端成功" + " " + new Date() + " " + ctx.channel().getRemoteAddress() + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelInactive(ChannelHandler ctx) {
        try {
            log.info("有客户端断开：{}", ctx.channel().getRemoteAddress());
            // 通知客户端连接端口了
            ctx.writeAndFlush("连接断开成功" + " " + new Date() + " " + ctx.channel().getRemoteAddress() + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelRead(ChannelHandler ctx, Object msg) {
        log.info("服务端收到： {} {}\r\n", new Date(), msg);
        ctx.writeAndFlush("服务端信息处理Success!\r\n");
    }

}
